import Card from '@/components/Card';
import Description from '@/components/Description';
import type { ProColumns } from '@/components/Pro/';
import { ProForm, ProFormInstance, ProTable } from '@/components/Pro/';
import {
  otaConfigControllerConfigPage as publish_list,
  otaConfigControllerPublish as ota_publish,
  otaConfigControllerUploadConfig as Uploadfile,
} from '@/services/ess/otaConfig';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { UploadOutlined } from '@ant-design/icons';
import { Button, message, Space, Upload } from 'antd';
import { DescriptionsItemType } from 'antd/es/descriptions';
import React, { useEffect, useRef, useState } from 'react';
import { useIntl, useSearchParams } from 'umi';
import styles from '../index.less';

const UpdateDetail: React.FC = () => {
  const { error } = message;
  const formRef = useRef<ProFormInstance>();
  const [searchParams] = useSearchParams();
  console.log(searchParams);
  const [deviceOptions, setDeviceOptions] = useState([]);
  const [packageName, setPackageName] = useState<string>('');
  const [versionFile, setFile] = useState<File>();
  // const stationId = searchParams.get('id');
  // const otaStatus = searchParams.get('otaStatus');
  // const configUpdateTime = searchParams.get('configUpdateTime');
  // const stationName = searchParams.get('stationName');
  const {
    id: stationId,
    otaStatus,
    configUpdateTime,
    stationName,
  } = JSON.parse(sessionStorage.getItem('SiteConfigurationParams'));

  const [isUploadSuccess, setIsUploadSuccess] = useState(false);
  const [isUploadSuccessUP, setIsUploadSuccessUp] = useState(false);
  const [publistId, setPublistId] = useState('');
  const intl = useIntl();
  console.log(intl);

  const [baseDes, setBaseDes] = useState<DescriptionsItemType[]>([
    {
      label: intl.formatMessage({
        id: 'remoteUpgradeMangment.siteConfigurationManagement.IPCstatus',
      }),
      key: 'otaStatus',
      children: '',
    },
    {
      label: intl.formatMessage({
        id: 'remoteUpgradeMangment.siteConfigurationManagement.updateTime',
      }),
      key: 'configUpdateTime',
      children: '',
    },
  ]);
  const [ProTableData, setProTableData] = useState<any>([]);

  const tableColumns: ProColumns<any>[] = [
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.siteConfigurationManagement.code' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
    },
    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.siteConfigurationManagement.updateTime',
      }),
      dataIndex: 'createdTime',
      key: 'createdTime',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.siteConfigurationManagement.Updatestatus',
      }),
      dataIndex: 'updateStatus',
      key: 'updateStatus',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <span>
            {
              deviceOptions?.filter((item) => {
                return Number(item.value) === Number(record?.updateStatus);
              })[0]?.label
            }
          </span>
        );
      },
    },
    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.componentManagement.upgradePackageStoragePath',
      }),
      dataIndex: 'fileUrl',
      key: 'fileUrl',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.remarks' }),
      dataIndex: 'updateDesc',
      key: 'updateDesc',
      hideInSearch: true,
    },
  ];
  useEffect(() => {
    (async () => {
      const dictOption = await fetchDictInfo(DATABASE_TYPE_ENUM.ONLINE_STATUS);
      const stateMap = dictOption.find((item) => item.value === otaStatus)?.label;
      const getBaseDes = baseDes.map((item) => ({
        ...item,
        children:
          item.key === 'otaStatus'
            ? stateMap
            : configUpdateTime === 'null'
            ? '--'
            : configUpdateTime,
      }));

      setBaseDes(getBaseDes);
      fetchDictInfo(DATABASE_TYPE_ENUM.OTA_LEVE_STATUS).then((res) => {
        setDeviceOptions(res);
      });

      let params = {
        current: '1',
        pageSize: '20',
        stationId: stationId,
      };

      let reslut = await publish_list(params);
      setProTableData(reslut?.data.records || []);
    })();
  }, []);

  return (
    <>
      <div className={styles.headerDesc}>
        <div className={styles.headerDesc_title_wrap}>
          <span className={styles.title1}>
            {intl.formatMessage({ id: 'remoteUpgradeMangment.other.Plantconfigurationupdate' })}
          </span>
          <span className={styles.title2}>({stationName})</span>
        </div>
        <Description items={baseDes}></Description>
        <div style={{ marginTop: 20 }}>
          <ProForm
            layout="inline"
            formRef={formRef}
            labelCol={{ style: { width: 160 } }}
            submitter={{
              render: () => (
                <Space>
                  <Button
                    key="upload"
                    type="primary"
                    disabled={!isUploadSuccessUP}
                    onClick={async () => {
                      try {
                        let result = await Uploadfile(
                          {
                            stationId: stationId,
                          },
                          {},
                          versionFile,
                        );
                        if (result.success) {
                          console.log(result, '成功结果');
                          setPublistId(result?.data.id);
                          setIsUploadSuccess(true);
                          message.success('上传成功');
                        }
                      } catch (error) {
                        setIsUploadSuccess(false);
                        console.log(error);
                      }
                    }}
                  >
                    {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.upload' })}
                  </Button>
                  <Button
                    key="issue"
                    type="primary"
                    disabled={!isUploadSuccess}
                    onClick={async () => {
                      let param = {
                        id: publistId,
                      };
                      try {
                        let result = await ota_publish(param);
                        // 下发逻辑
                        if (result.success) {
                          message.success('下发成功');
                        }
                      } catch (error) {
                        console.log(error);
                      }
                    }}
                  >
                    {intl.formatMessage({ id: 'remoteUpgradeMangment.other.release' })}
                  </Button>
                </Space>
              ),
              submitButtonProps: {
                text: '提交',
              },
              resetButtonProps: false,
            }}
          >
            <ProForm.Item
              label={intl.formatMessage({
                id: 'remoteUpgradeMangment.componentManagement.otaFile',
              })}
              name="file"
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'remoteUpgradeMangment.requiredFields.selectFile',
                  }),
                },
              ]}
            >
              <Space>
                <Upload
                  maxCount={1}
                  accept=".zip, .rar"
                  beforeUpload={(file) => {
                    setPackageName(file.name);
                    console.log(packageName);
                    setFile(file);
                  }}
                  customRequest={(req) => {
                    const { onSuccess, onError } = req;
                    const { file } = req;
                    if (file.size / 1024 / 1024 > 500) {
                      error(
                        intl.formatMessage({
                          id: 'systemManagement.neddTochange.fileMax500m',
                        }),
                      );
                      onError('文件大小超过500M，请重新上传');
                      setIsUploadSuccessUp(false);
                      return false;
                    } else {
                      console.log('我这边文件上传成功');
                      setIsUploadSuccessUp(true);
                      onSuccess({ result_status: true });
                    }
                  }}
                  onRemove={() => {
                    setIsUploadSuccessUp(false);
                    setIsUploadSuccess(false);
                  }}
                >
                  <Button icon={<UploadOutlined />}></Button>
                </Upload>
              </Space>
            </ProForm.Item>
          </ProForm>
        </div>
      </div>
      <Card
        title={intl.formatMessage({ id: 'remoteUpgradeMangment.other.configurationreleaserecord' })}
        style={{ marginTop: '40px' }}
      >
        <ProTable
          columns={tableColumns}
          dataSource={ProTableData}
          search={false}
          rowKey={'pageIndex'}
        ></ProTable>
      </Card>
    </>
  );
};

export default UpdateDetail;
